//
//  LSUserAccountViewModel.swift
//  MicroBlog
//
//  Created by lj on 15/9/6.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import ReactiveCocoa

/// 用户账户视图模型
class LSUserAccountViewModel: NSObject {

    /// 单例
    static let sharedUserAccountViewModel = LSUserAccountViewModel()
    
    override init() {
        userAccount = LSUserAccount.loadUserAccount()
    }
    /// 账户
    var userAccount : LSUserAccount?
    
    /// accessToken
    var  accessToken:String? {
        return userAccount?.access_token
    }
    /// 用户登录标记
    var userLogon: Bool {
        return accessToken != nil
    }
    
    var avatarUrl:NSURL? {
        return NSURL(string: userAccount?.avatar_large ?? "")
    }
    
    
    //MARK: -加载网络数据
    /// 加载用户accessToken & 用户信息
    func loadUserAccount(code: String)->RACSignal {
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            NetworkTools.sharedNetworkTools.loadAccessToken(code).doNext({ (result) -> Void in
      
                let userAccount = LSUserAccount(dict: result as! [String : AnyObject])
                
                //设置当前的账户属性
                self.userAccount = userAccount
                printLog(userAccount)
                
                NetworkTools.sharedNetworkTools.loadUserInfo(userAccount.uid!).subscribeNext({ (result) -> Void in
                    
                    let dict = result as! [String:AnyObject]
                    //设置账号属性
                    userAccount.name = dict["name"] as? String
                    userAccount.avatar_large = dict["avatar_large"] as? String
                    
                    printLog(userAccount)
                    
                    //保存账号
                    userAccount.saveUserAccount()
                    
                    // 通知订阅者网络数据加载完成
                    subscriber.sendCompleted()
                    
                    }, error: { (error) -> Void in
                        subscriber.sendError(error)
                })
                
            }).subscribeError({ (error) -> Void in
                subscriber.sendError(error)
            })
            return nil
        })
    }
    
    
}
